<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :list-type-info="listTypeInfo"
        :clear-type="clearType"
        :slipSelectRequest="slipSelectRequest"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            @change="timeChange"
            v-model="operateTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
      <div class="display-flex">
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>
    <TableContainer
      class="groupFlag-container"
      :isGroupSearch="true"
      v-model:data="groupSelectInfo.data"
      :field-list="tableInfo.fieldList"
      :checkBox="false"
      :tabIndex="false"
      :pager="false"
      :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
      @exChange="exChange"
      @sortChange="sortChange"
      :span-method="arraySpanMethod"
      :row-class-name="tableRowClassName"
      :allSummary="true"
      :allSummaryData="groupSelectInfo.allSummaryData"
    />

    <!--  偏好设置  -->
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="outboundDetails">
import { ElMessage } from 'element-plus'
import {
  getOutboundDetailsCustomizeAll,
  getOutboundDetailsCustomizeGroups,
  printOutboundDetails,
  outboundDetailsExcel,
} from '@/api/statisticalReports'
import { fatchTemplateByCode } from '@/api/base'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const groupFlag = ref(true)
const clearType = ref(true)
const slipSelectRequest = ref(true)
const listTypeInfo = ref({
  typeList: [],
})
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const groupSelectInfo = ref({
  options: [],
  selections: ['inventoryCategoriesValue-inventoryCategories'],
  data: [],
  allSummaryData: {
    data: [],
    fieldList: [
      {
        label: '总金额',
        value: 'sumAmount',
        type: 'column',
        formatter: proxy.$fn.TripartiteMethod,
      },
    ],
  },
})
const filterInfo = ref({
  query: {
    sortString: '',
    groupMap: {},
    groups: ['inventoryCategoriesValue-inventoryCategories'],
    customizeUserVO: {},
    queryMap: {
      operateTime: {
        queryType: 'BETWEEN',
        value:
          moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
            'YYYY-MM-DD HH:mm:ss'
          ) +
          ',' +
          moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '打印',
      event: printList,
      show: proxy.$permission('outboundDetails:print'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcelList,
      show: proxy.$permission('outboundDetails:excel'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [],
  },
})

const operateTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
    'YYYY-MM-DD HH:mm:ss'
  ),
  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
])
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const preferenceInfo = ref({
  visible: false,
})
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = proxy.$fn.deepClone(filterInfo.value.query)
  }
  await getOutboundDetailsCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      let sumAmount = 0
      if (data && data.length) {
        for (let i = 0; i < data.length; i++) {
          sumAmount = proxy.$fn.accAdd(sumAmount, data[i].sumAmount)
        }
      }
      groupSelectInfo.value.allSummaryData.data = [
        {
          sumAmount: sumAmount,
        },
      ]
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      console.log(11111, 'queryIn')
      getOutboundDetailsCustomizeAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
  }
}

function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    } else {
      return [0, 0]
    }
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'OutboundDetailsVO-com.slip.spd.entity.vo.dataquery.OutboundDetailsVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )

      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      let queryIn = proxy.$route.params.query
      console.log(queryIn, 'queryIn')
      if (queryIn) {
        filterInfo.value.query.queryMap = {
          ...filterInfo.value.query.queryMap,
          ...queryIn.queryMap,
        }
        if (queryIn.queryMap.operateTime) {
          operateTime.value = queryIn.queryMap.operateTime.value.split(',')
        }
      }
      slipSelectRequest.value = _slipSelectRequest
      getCustomizeGroupsList()
    }
  })
}
function search() {
  if (operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      if (groupSelectInfo.value.selections.length > 0) {
        getCustomizeGroupsList()
      } else {
        groupSelectInfo.value.data = []
        tableInfo.value.initCurpage = Math.random()
        tableInfo.value.refresh = Math.random()
      }
    }
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  operateTime.value =
    filterInfo.value.query.queryMap.operateTime.value.split(',')
  search()
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.operateTime.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.operateTime.value = null
  }
}

function printList() {
  if (operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      fatchTemplateByCode({
        resourceCode: 'outboundDetails:print',
        isDefault: 1,
      }).then((res) => {
        if (res && res.success) {
          let temp = proxy.$fn.getPrintTemp(res.data[0])
          getPrintData(temp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}
function getPrintData(temp) {
  let params = {
    customizeDto: filterInfo.value.query,
  }
  printOutboundDetails(params).then((resp) => {
    if (resp && resp.success) {
      let data = proxy.$fn.deepClone(resp.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function exportExcelList() {
  console.log(12121)
  if (operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      outboundDetailsExcel(filterInfo.value.query).then((resp) => {
        if (resp) {
          proxy.$fn.parseExcel(resp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}
async function setPreferenceCallback(obj) {
  slipSelectRequest.value = !slipSelectRequest.value
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}

let obj = {
  operateTime: {
    label: '操作时间',
    value: 'operateTime',
    componentType: 'dateTime',
    slot: true,
    hidden: true,
    show: false,
  },
  deptCode: {
    label: '科室编码',
    value: 'deptCode',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'text',
    componentType: 'input',
    hidden: false,
    show: true,
  },
  deptName: {
    label: '科室名称',
    value: 'deptName',
    formatter: proxy.$fn.TripartiteMethod,
    componentType: 'input',
    hidden: false,
    show: true,
  },

  inventoryCategoriesValue: {
    label: '库存类别',
    value: 'inventoryCategoriesValue',
    asValue: 'inventoryCategories',
    componentType: 'select-model',
    code: 'inventory_categories',
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    hidden: false,
    show: true,
  },
  exportStoreTypeValue: {
    label: '出入库类型',
    value: 'exportStoreTypeValue',
    asValue: 'exportStoreType',
    componentType: 'select-model',
    code: 'export_store_type',
    hidden: false,
    show: false,
  },
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'export_affair_type',
    onlyShowOption: [
      '1',
      '2',
      '4',
      '6',
      '8',
      '10',
      '11',
      '15',
      '18',
      '20',
      '22',
      '53',
      '47',
      '48',
      '49',
      '50',
      '51',
    ],
    show: false,
    hidden: true,
  },
}

let export_affair_type =
  proxy.$store.state.permission.dict['export_affair_type']
if (export_affair_type && export_affair_type.length) {
  export_affair_type.forEach((item) => {
    if (item.code != '23' || item.code != '39' || item.code != '56') {
      obj.typeValue.onlyShowOption.push(item.code)
    }
  })
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})

getCustomize()
</script>

<style scoped></style>
